package com.cloudkinto.controller.stock;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.extentity.StockSnapshotPageDto;
import com.cloudkinto.extentity.stock.ShopStockRecordDto;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.orderinput.vo.InputOrderMarkPackageReq;
import com.cloudkinto.service.orderinput.vo.InputOrderMarkReq;
import com.cloudkinto.service.orderinput.vo.InputOrderMarkSingleReq;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.vo.FreezeStockReq;
import com.cloudkinto.service.stock.vo.StockRecordReq;
import com.cloudkinto.service.stock.vo.record.StockRecordAddReq;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import com.cloudkinto.service.stock.vo.record.StockRecordSendReq;
import com.cloudkinto.service.stock.vo.record.StockRecordUpdateReq;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-10
 */
@RestController
@Api(tags = "库存管理模块")
@RequestMapping("/api/admin/stockRecord")
public class StockRecordController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(StockRecordController.class);

    @Autowired
    private StockRecordService service;
    @Autowired
    private ProductInfoService productInfoService;

    @UserSessionRequired
    @PostMapping()
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated StockRecordAddReq req) {
        Long userId = getCurrentUserId();
        return service.add(req, userId);
    }

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit();
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable Long id) {
        return service.updateInit(id);
    }

    @UserSessionRequired
    @PutMapping()
    @ApiOperation(value = "编辑", notes = "编辑")
    public SingleResult update(@RequestBody @Validated StockRecordUpdateReq req) {
        Long userId = getCurrentUserId();
        return service.update(req, userId);
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId(), getCurrentUserId());
    }

    @UserSessionRequired
    @PostMapping("sendOutInit")
    @ApiOperation(value = "发货初始化", notes = "发货初始化")
    public SingleResult sendOutInit() {
//        Long companyId = getCompanyId();
//        Long userId = getCurrentUserId();
        return service.sendOutInit();
    }

    @UserSessionRequired
    @PostMapping("sendOut")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult sendOut(@RequestBody @Validated StockRecordSendReq req) {
        Long companyId = getCompanyId();
        Long userId = getCurrentUserId();
        return service.sendOut(req, userId, companyId);
    }

    @UserSessionRequired
    @PostMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> listPage(@RequestBody @Validated StockRecordReq req) {
        Map map = new HashMap<>();
        map.put("keyword", req.getKeyword());
        map.put("shopId", req.getShopId());
        map.put("storageId", req.getStorageId());
        map.put("productType",req.getProductType());
        map.put("companyId", req.getCompanyId());
        map.put("current", req.getCurrent());
        map.put("pageSize", req.getPageSize());
        return service.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productListPage")
    @ApiOperation(value = "商品（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "productType", value = "产品类型"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult productListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String productType = request.getParameter("productType");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");

//        if (companyId != null) {
//            map.put("companyId", companyId + "");
//        }
        map.put("productType", productType);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        return productInfoService.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productType")
    @ApiOperation(value = "商品分类", notes = "查询（分页）")
    public SingleResult productType(HttpServletRequest request) {
        return productInfoService.productType();
    }

    /********************库存快照模块********************/

    @UserSessionRequired
    @GetMapping("/stockSnapshotPage")
    @ApiOperation(value = "库存快照查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "commoditySku", value = "OMS SKU"),
            @ApiImplicitParam(name = "startDate", value = "开始日期"),
            @ApiImplicitParam(name = "endDate", value = "结束日期")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockSnapshotPageDto.class)})
    public PageResult stockSnapshotPage(String current, String pageSize, String storageId,String companyId, String commoditySku, String startDate, String endDate) {
        Map<String, String> map = new HashMap<>();
        map.put("commoditySku", commoditySku);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("storageId", storageId);
        map.put("companyId", companyId);
        map.put("current", current);
        map.put("pageSize", pageSize);
        return service.getStockSnapshotPage(map);
    }

    @UserSessionRequired
    @GetMapping("/exportExcel")
    @ApiOperation(value = "库存快照导出Excel")
    @ApiImplicitParams({@ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "companyId", value = "公司标识"),
            @ApiImplicitParam(name = "commoditySku", value = "OMS SKU"),
            @ApiImplicitParam(name = "startDate", value = "开始日期"),
            @ApiImplicitParam(name = "endDate", value = "结束日期")})
    public SingleResult exportExcel(String companyId,String storageId, String commoditySku, String startDate, String endDate) throws IOException {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = simpleDateFormat.format(new Date());
        String fileName = "库存" + time +".xlsx";
        map.put("commoditySku", commoditySku);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("storageId", storageId);
        map.put("companyId",companyId);
        return SingleResult.success(service.exportExcel(map,fileName));
    }


    @UserSessionRequired
    @PutMapping("freezeStock")
    @ApiOperation(value = "冻结库存", notes = "冻结库存")
    public SingleResult freezeStock(@RequestBody @Validated FreezeStockReq req) {
        Long userId = getCurrentUserId();
        service.freezeStock(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/getStockRecord")
    @ApiOperation(value = "盘盈盘亏 盘点完成 获取店铺列表", notes = "盘盈盘亏 盘点完成 获取店铺列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "skuId"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "type", value = "操作类型 增加还是减少 0 增加 1 减少"),
            @ApiImplicitParam(name = "quantityType", value = "操作良品 还是 次品 good 良品 bad 次品")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "", response = ShopStockRecordDto.class)})
    public SingleResult getStockRecord(Long productId, Long storageId, Integer type, String quantityType) {
        return SingleResult.success(service.getStockRecord(productId, storageId, type, quantityType));
    }

}

